package xyz.labmem.main.tool;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import xyz.labmem.main.config.jackson.JacksonObjectMapper;
import xyz.labmem.main.error.FuncException;

/**
 * Jackson序列化工具
 * Created by Lty
 * Created in 11:57 2020-3-6
 */
public class Jackson {

    private static final ObjectMapper Jackson = new JacksonObjectMapper().serializingObjectMapper();

    /**
     * 对象转json字符串
     *
     * @param object 对象
     * @return json
     * @throws JsonProcessingException
     */
    public static String ObjectToJson(Object object) {
        try {
            return Jackson
                    .writerWithDefaultPrettyPrinter()
                    .writeValueAsString(object);
        } catch (JsonProcessingException e) {
            new FuncException("ObjectToJson 错误！", e);
            return null;
        }

    }

    /**
     * json字符串转回对象
     *
     * @param json   json
     * @param eClass 对象Class
     * @return 对象实体
     * @throws JsonProcessingException
     */
    public static  <E> E JsonToObject(String json, Class<E> eClass) {
        try {
            return Jackson
                    .readValue(json, eClass);
        } catch (JsonProcessingException e) {
            new FuncException("JsonToObject 错误！", e);
            return null;
        }

    }

}
